<template>
  <div>
    <a-layout-content class="hotelMant">
      <div class="hotelMant-header">
        <div class="hotelMant-tit">
          <p>酒店列表</p>
        </div>
        <div class="hotelMant-search">
          <span style="margin-right: 4px">搜索：省、市</span>
          <a-space>
            <a-select
              v-model:value="provinceSearch"
              style="width: 120px"
              @change="getSearchMarket"
            >
              <a-select-option value="">默认值</a-select-option>
              <a-select-option :value="item.value" v-for="item in provinceData">
                {{ item.label }}
              </a-select-option>
            </a-select>
            <a-select
              v-model:value="secondCitySearch"
              style="width: 120px"
              @change="getSearchDistinguish"
            >
              <a-select-option
                :value="item.value"
                v-for="item in marketSearcgData"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-space>
        </div>
      </div>
      <div class="hotelMant-headerFun">
        <a-button type="primary" class="addHotel" @click="addHotel"
          >添加酒店</a-button
        >
      </div>
      <div class="hotelMant-content">
        <a-table
          :columns="columns"
          :data-source="data"
          class="components-table-demo-nested"
          :pagination="{
            total: totalNum,
            pageSizeOptions: pageSizeOptions,
          }"
          @change="onShowSizeChange"
          rowKey="id"
          :customRow="customRow"
          @expand="onShowSizeExpand"
          @expandedRowsChange="onExpandedRowsChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <div v-if="record.is_ban === '0'">
                <a-button type="primary" @click="bindEdit">编辑</a-button>
                <a-button type="danger" @click="bindDisable(1)">禁用</a-button>
              </div>
              <div v-else>
                <a-button type="primary" @click="bindDisable(0)">启用</a-button>
              </div>
            </template>
          </template>
          <template #expandedRowRender>
            <a-button type="primary" class="addHotel" @click="addRoom(0)"
              >添加房间</a-button
            >
            <a-table
              :columns="innerColumns"
              :data-source="innerData"
              :pagination="false"
              :customRow="customRowSub"
            >
              <template #bodyCell="{ column }">
                <template v-if="column.key === 'operation'">
                  <a-button type="primary" @click="addPassword"
                    >添加密码</a-button
                  >
                  <a-button type="primary" @click="addRoom(1)"
                    >编辑房间</a-button
                  >
                  <a-button type="danger" @click="del(0)">删除密码</a-button>
                  <a-button type="danger" @click="del(1)">删除房间</a-button>
                </template>
              </template>
            </a-table>
          </template>
        </a-table>
      </div>
    </a-layout-content>
    <!-- 添加对话框 -->
    <a-modal
      v-model:visible="Addvisible"
      title="添加酒店"
      @ok="handleAdd"
      @cancel="bindAddClose"
    >
      <a-input
        v-model:value="nameVal"
        placeholder="填写名字"
        style="margin-bottom: 20px"
      />
      <div style="margin-bottom: 20px">
        <span style="margin-right: 4px">省、市、区：</span>
        <a-space>
          <a-select
            v-model:value="province"
            style="width: 120px"
            @change="getMarket"
          >
            <a-select-option :value="item.value" v-for="item in provinceData">
              {{ item.label }}
            </a-select-option>
          </a-select>
          <a-select
            v-model:value="secondCity"
            style="width: 120px"
            @change="getDistinguish"
          >
            <a-select-option :value="item.value" v-for="item in marketData">
              {{ item.label }}
            </a-select-option>
          </a-select>
          <a-select
            v-model:value="areasVal"
            style="width: 120px"
            @change="getAddress"
          >
            <a-select-option :value="item.value" v-for="item in areas">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-space>
      </div>
      <a-input
        v-model:value="addressVal"
        placeholder="填写详细地址"
        style="margin-bottom: 20px"
      />
      <a-input
        v-model:value="contactsVal"
        placeholder="联系人"
        style="margin-bottom: 20px"
      />
      <a-input
        v-model:value="phoneVal"
        placeholder="输入手机号"
        style="margin-bottom: 20px"
      />
      <a-input
        v-model:value="wechatVal"
        placeholder="输入微信号"
        style="margin-bottom: 20px"
      />
      <a-upload
        v-model:file-list="files"
        action="http://47.107.231.209:2224/admin/v1/files"
        :headers="headers"
        list-type="picture"
        @change="handleChangeFile"
        :maxCount="3"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          上传图片
        </a-button>
      </a-upload>
      <a-upload
        v-model:file-list="filesLogo"
        action="http://47.107.231.209:2224/admin/v1/files"
        :headers="headers"
        list-type="picture"
        @change="handleChangeLogo"
        :maxCount="1"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          上传LOGO
        </a-button>
      </a-upload>
    </a-modal>
    <!-- 编辑对话框 -->
    <a-modal
      v-model:visible="Editvisible"
      title="编辑酒店"
      @ok="handleEdit"
      @cancel="bindClose"
    >
      <a-input
        v-model:value="editNameVal"
        placeholder="Basic usage"
        style="margin-bottom: 20px"
      />
      <div style="margin-bottom: 20px">
        <span style="margin-right: 4px">省、市、区：</span>
        <a-space>
          <a-select
            v-model:value="provinceEdit"
            style="width: 120px"
            @change="getMarket"
          >
            <a-select-option :value="item.value" v-for="item in provinceData">
              {{ item.label }}
            </a-select-option>
          </a-select>
          <a-select
            v-model:value="secondCityEdit"
            style="width: 120px"
            @change="getDistinguish"
          >
            <a-select-option :value="item.value" v-for="item in marketData">
              {{ item.label }}
            </a-select-option>
          </a-select>
          <a-select
            v-model:value="areasValEdit"
            style="width: 120px"
            @change="getAddress"
          >
            <a-select-option :value="item.value" v-for="item in areas">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-space>
      </div>
      <a-input
        v-model:value="editAddressVal"
        placeholder="Basic usage"
        style="margin-bottom: 20px"
      />
      <a-input
        v-model:value="editContactsVal"
        placeholder="Basic usage"
        style="margin-bottom: 20px"
      />
      <a-input
        v-model:value="editPhoneVal"
        placeholder="Basic usage"
        style="margin-bottom: 20px"
      />
      <a-input
        v-model:value="editWeichatVal"
        placeholder="Basic usage"
        style="margin-bottom: 20px"
      />
      <a-upload
        v-model:file-list="filesEdit"
        action="http://47.107.231.209:2224/admin/v1/files"
        :headers="headers"
        list-type="picture"
        @change="handleChangeFile"
        :maxCount="3"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          上传图片
        </a-button>
      </a-upload>
      <a-upload
        v-model:file-list="filesLogoEdit"
        action="http://47.107.231.209:2224/admin/v1/files"
        :headers="headers"
        list-type="picture"
        @change="handleChangeLogo"
        :maxCount="1"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          上传LOGO
        </a-button>
      </a-upload>
    </a-modal>
    <!-- 禁用/启用对话框 -->
    <a-modal
      v-model:visible="Disablevisible"
      title="确认执行动作内容"
      @ok="handleDisable"
    >
      <p>
        当前执行动作内容是<span style="font-weight: bold; font-size: 20px"
          >[{{ activeEn === 1 ? "禁用" : "启用" }}]</span
        >,是否确认执行!!!!
      </p>
    </a-modal>
    <!-- 添加/编辑房间对话框 -->
    <a-modal
      v-model:visible="visibleRoom"
      title="添加房间"
      @ok="handleAddRoom"
      @cancel="emptyRoom"
    >
      <span>房间状态：</span>
      <a-select
        ref="select"
        v-model:value="roomType"
        style="width: 120px"
        @change="ChangeRoomType"
      >
        <a-select-option value="0">未出租</a-select-option>
        <a-select-option value="1">已出租</a-select-option>
      </a-select>
      <a-textarea
        v-model:value="roomIntroduce"
        placeholder="房间介绍"
        :auto-size="{ minRows: 2, maxRows: 10 }"
        :maxlength="120"
        show-count
        style="margin: 10px 0"
      />
      <span>房间类型</span>
      <a-input
        style="margin-bottom: 10px"
        v-model:value="roomFrom"
        placeholder="例：一室单人房"
      />
      <span>房间详情</span>
      <a-input
        style="margin-bottom: 10px"
        v-model:value="roomDetail"
        placeholder="例：无早餐·整套·1居 1张 2*1.5米大床·1人"
      />
      <span>房间押金</span>
      <a-input
        style="margin-bottom: 10px"
        prefix="￥"
        suffix="RMB"
        v-model:value="roomDeposit"
      />
      <span>房间价格</span>
      <a-input
        style="margin-bottom: 10px"
        prefix="￥"
        suffix="RMB"
        v-model:value="roomPrice"
      />
      <a-upload
        v-model:file-list="filesRoom"
        action="http://47.107.231.209:2224/admin/v1/files"
        :headers="headers"
        list-type="picture"
        @change="handleChangeFile"
        :maxCount="5"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          上传图片
        </a-button>
      </a-upload>
    </a-modal>

    <!-- 房间密码添加对话框 -->
    <a-modal
      v-model:visible="visiblePassword"
      title="添加密码"
      @ok="handleAddPassword"
    >
      <a-input v-model:value="passwordValue" placeholder="密码" />
      <a-range-picker v-model:value="valueTime" :format="dateFormat" />
    </a-modal>
    <!-- 删除确认框 -->
    <a-modal v-model:visible="visibleDel" :title="delText" @ok="handleDel">
      <p style="color: red">确认是否删除！！！！！！</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { UploadOutlined } from "@ant-design/icons-vue";
import { Myrequest } from "@/network/request";
import { message } from "ant-design-vue";
import cascaderOptions, { DivisionUtil } from "@pansy/china-division";
//安装的china-division插件，插件内容是中国（包含港澳台）省市区
const divisionUtil = new DivisionUtil(cascaderOptions); 
const dataList = divisionUtil.getSourceData(); //总数据
const token = sessionStorage.getItem("token");//获取存在前端数据库的token
const activeNum = ref(0); //判断值，用于在什么样的操作下做什么样的事
const dateFormat = "YYYY-MM-DD"; //设置日期格式
// 请求头，antdVue文件上传的请求头
const headers = {
  Authorization: token,
};

const totalNum = ref([]); //总条数
const pageSizeOptions = ref(["5", "10", "15", "20"]); //一页选择展示多少数据
// 封装的默认酒店列表加载值函数
function Refresh() {
  Myrequest("GET", "/admin/v1/hotel", {
    limit: 10,
    page: 1,
  }).then((res) => {
    data.value = res.data.data;
    totalNum.value = res.data.total;
    res.data.data.forEach((item) => {
      item.Caddress = item.province + item.city + item.district + item.address;
      switch (item.is_ban) {
        case "0":
          item.is_banText = "启用";
          break;
        case "1":
          item.is_banText = "禁用";
          break;
        default:
          item.is_banText = "不知道什么状态";
          break;
      }
    });
  });
}
// 将中国标准时间转为标准时间
// 中国标准时间-格式： Sat Apr 09 2022 08:00:00 GMT+0800 (中国标准时间)
// 标准时间-格式： 2022-04-09
function getSimpleDate(date) {
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? "0" + m : m;
  var d = date.getDate();
  d = d < 10 ? "0" + d : d;
  // var h = date.getHours();
  // var minute = date.getMinutes();
  // minute = minute < 10 ? ('0' + minute) : minute;
  // var s = date.getSeconds();
  // s = s < 10 ? '0' + s : s;
  return y + "-" + m + "-" + d + " ";
}

// 主表格的字段
const columns = [
  {
    title: "名字",
    dataIndex: "name",
    key: "name",
    width: 90,
    align: "center",
  },
  {
    title: "地址",
    dataIndex: "Caddress",
    width: 200,
    align: "center",
  },
  {
    title: "电话",
    dataIndex: "phone",
    key: "phone",
    width: 200,
    align: "center",
  },
  {
    title: "微信",
    dataIndex: "wechat",
    key: "wechat",
    width: 200,
    align: "center",
  },
  {
    title: "联系人",
    dataIndex: "linkman",
    key: "linkman",
    width: 200,
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "is_banText",
    key: "is_banText",
    width: 200,
    align: "center",
  },
  {
    title: "操作",
    key: "operation",
    width: 200,
    align: "center",
  },
];
// 主表格的原数据数组
const data = ref([]);
// 子表格的字段
const innerColumns = [
  {
    title: "房间状态",
    dataIndex: "status",
    key: "status",
    width: 90,
    align: "center",
  },
  {
    title: "房间简介",
    dataIndex: "content",
    key: "state",
    width: 120,
    align: "center",
  },
  {
    title: "房间押金",
    dataIndex: "old_price",
    key: "old_price",
    width: 90,
    align: "center",
  },
  {
    title: "房间租金",
    dataIndex: "now_price",
    key: "now_price",
    width: 90,
    align: "center",
  },
  {
    title: "房间密码",
    dataIndex: "passwordRoom",
    key: "passwordRoom",
    width: 90,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
    width: 200,
    align: "center",
  },
];
// 子表格的原数据数组
const innerData = ref([]);
//  搜索框
const provinceSearch = ref(""),
  secondCitySearch = ref("");
const marketSearcgData = ref([]);
const getSearchMarket = (value) => {
  if (value === "") {
    secondCitySearch.value = "";
    Refresh();
  } else {
    let aa = dataList.findIndex((n) => {
      return n.value === value;
    });
    secondCitySearch.value = "";
    marketSearcgData.value = dataList[aa].children;
    // 获取省的label
    provinceText.value = dataList[aa].label;
    // 搜索获取省字段下的数据
    Myrequest("GET", "/admin/v1/hotel", {
      province: provinceText.value,
    }).then((res) => {
      data.value = res.data.data;
      totalNum.value = res.data.total;
      res.data.data.forEach((item) => {
        item.Caddress =
          item.province + item.city + item.district + item.address;
        switch (item.is_ban) {
          case "0":
            item.is_banText = "启用";
            break;
          case "1":
            item.is_banText = "禁用";
            break;
          default:
            item.is_banText = "不知道什么状态";
            break;
        }
      });
      message.success("搜索到有：" + res.data.total + "条结果");
    });
  }
};

const getSearchDistinguish = (value) => {
  let bb = marketSearcgData.value.findIndex((m) => {
    return m.value === value;
  });
  areasVal.value = "";
  areas.value = marketSearcgData.value[bb].children;
  // 获取市的label
  secondCityText.value = marketSearcgData.value[bb].label;
  Myrequest("GET", "/admin/v1/hotel", {
    province: provinceText.value,
    city: secondCityText.value,
  }).then((res) => {
    data.value = res.data.data;
    totalNum.value = res.data.total;
    res.data.data.forEach((item) => {
      item.Caddress = item.province + item.city + item.district + item.address;
      switch (item.is_ban) {
        case "0":
          item.is_banText = "启用";
          break;
        case "1":
          item.is_banText = "禁用";
          break;
        default:
          item.is_banText = "不知道什么状态";
          break;
      }
    });
    message.success("搜索到有：" + res.data.total + "条结果");
  });
};

// 首次加载
onMounted(() => {
  filesEdit.value = [];
  filesLogoEdit.value = [];
  Refresh();
});

// 点击页码
const onShowSizeChange = (page, pageSize) => {
  Myrequest("GET", "/admin/v1/hotel", {
    limit: page.pageSize,
    page: page.current,
  }).then((res) => {
    data.value = res.data.data;
    res.data.data.forEach((item) => {
      item.Caddress = item.province + item.city + item.district + item.address;
      switch (item.is_ban) {
        case "0":
          item.is_banText = "启用";
          break;
        case "1":
          item.is_banText = "禁用";
          break;
        default:
          item.is_banText = "不知道什么状态";
          break;
      }
    });
  });
};

// 点击新的表格关闭原先表格
const onExpandedRowsChange = (rows) => {
  if (rows.length > 1) {
    rows.shift();
  }
};
// 点击表格行展开图标
const hotelId = ref(""); // 酒店ID
const onShowSizeExpand = (value, record) => {
  innerData.value = record.room;
  hotelId.value = record.id;
  record.room.forEach((item) => {
    item.now_price = item.RoomPrice.now_price;
    if (item.RoomPassword.length === 0) {
      item.passwordRoom = "未设置密码";
      return;
    }
    item.passwordRoom = item.RoomPassword[0].password;
  });
};

// 添加按钮
const Addvisible = ref(false);
const province = ref(""), //省的code
  secondCity = ref(""), //市的code
  areasVal = ref(""), //区的code
  contactsVal = ref(""),//联系人
  wechatVal = ref(""),//微信值
  phoneVal = ref(""),//手机号
  addressVal = ref(""),//详细地址
  nameVal = ref(""); //名字

const provinceText = ref("");//省
const secondCityText = ref("");//市
const areasText = ref("");//区

const files = ref([]);
const filesLogo = ref([]);

const fileHotelFile = ref([]), //上传文件的原数组
  fileHoteFileStr = ref("");//将上传文件的内容拼接字段

const fileHotelLogo = ref("");

const phone = /^[1]([3-9])[0-9]{9}$/;
const addHotel = () => {
  Addvisible.value = true;
};

const handleAdd = () => {
  let strFile = "";
  if (
    nameVal.value === "" ||
    provinceText.value === "" ||
    secondCityText.value === "" ||
    areasText.value === "" ||
    contactsVal.value === "" ||
    addressVal.value === "" ||
    phoneVal.value === "" ||
    wechatVal.value === ""
  ) {
    message.warning("选项框没有填写完成！！！");
    return;
  }
  if (!phone.test(phoneVal.value)) {
    message.warning("手机号格式不正确");
    return;
  }

  if (fileHotelFile.value.length === 0 || fileHotelLogo.value === "") {
    message.warning("图片还没上传");
    return;
  }
  fileHotelFile.value.forEach((item) => {
    strFile += item + ",";
  });
  fileHoteFileStr.value = strFile.substring(0, strFile.length - 1);
  activeNum.value = 0;
  Myrequest("POST", "/admin/v1/hotel", {
    name: nameVal.value,    //名字
    province: provinceText.value, //省
    city: secondCityText.value,//市
    district: areasText.value,//区
    linkman: contactsVal.value,//联系人
    address: addressVal.value,//详细地址
    phone: phoneVal.value,//手机号
    wechat: wechatVal.value,//微信号
    img_urls: fileHoteFileStr.value,//图片字段
    logo_url: fileHotelLogo.value,//logo图片字段
  }).then((res) => {
    switch (res.code) {
      case 200:
        message.success("添加成功");
        Addvisible.value = false;
        Refresh();
        break;
    }
  });

};

// 关闭清空数据
const bindAddClose = () => {
  files.value = [];
  filesLogo.value = [];
};

// 省
const provinceData = divisionUtil.getProvinces(); //省
const marketData = ref([]),
  areas = ref([]);
// 市
const getMarket = (value) => {
  let aa = dataList.findIndex((n) => {
    return n.value === value;
  });
  secondCity.value = "";
  areasVal.value = "";
  marketData.value = dataList[aa].children;
  // 获取省的label
  provinceText.value = dataList[aa].label;
  console.log(provinceText.value);
};
// 区
const getDistinguish = (value) => {
  let bb = marketData.value.findIndex((m) => {
    return m.value === value;
  });
  areasVal.value = "";
  areas.value = marketData.value[bb].children;
  // 获取市的label
  secondCityText.value = marketData.value[bb].label;
  console.log(secondCityText.value);
};

const getAddress = (value) => {
  let cc = areas.value.findIndex((g) => {
    return g.value === value;
  });
  areasText.value = areas.value[cc].label;
};

const customRow = (record) => {
  return {
    onClick: (event) => {
      console.log(record);
      editID.value = record.id;
    },
  };
};

// 编辑
const Editvisible = ref(false);
const editNameVal = ref(""),
  editAddressVal = ref(""),//详细地址
  editContactsVal = ref(""),//联系人
  editPhoneVal = ref(""),//手机号
  editWeichatVal = ref(""),//微信号
  provinceEdit = ref(""), //省
  secondCityEdit = ref(""),//市
  areasValEdit = ref(""),//区
  editID = ref("");

const editImage = ref([]);
const editLogoImage = ref("");

const filesEdit = ref([]);
const filesLogoEdit = ref([]);

const bindEdit = () => {
  Editvisible.value = true;
  activeNum.value = 1;
  // 使用延时器的方式异步获取数据
  setTimeout(() => {
    console.log();
    Myrequest("get", "/admin/v1/hotel/" + editID.value).then((res) => {
      console.log(res);
      editNameVal.value = res.data.name;
      editAddressVal.value = res.data.address;
      editContactsVal.value = res.data.linkman;
      editPhoneVal.value = res.data.phone;
      editWeichatVal.value = res.data.wechat;
      provinceEdit.value = res.data.province;
      secondCityEdit.value = res.data.city;
      areasValEdit.value = res.data.district;
      let aa = dataList.findIndex((n) => {
        return n.label === provinceEdit.value;
      });
      marketData.value = dataList[aa].children;
      let bb = marketData.value.findIndex((m) => {
        return m.label === secondCityEdit.value;
      });
      areas.value = marketData.value[bb].children;
      if (res.data.logo_url) {
        editLogoImage.value = res.data.logo_url;
        let arrLogo = res.data.logo_url.split("/");
        let lenLogo = arrLogo.length;
        filesLogoEdit.value.push({
          url: res.data.logo_url,
          name: arrLogo[lenLogo - 1],
        });
      }
      if (res.data.img_url.length < 0) return;
      res.data.img_url.forEach((item) => {
        let arr = item.split("/");
        let len = arr.length;
        editImage.value.push(item);
        console.log(editImage.value);
        filesEdit.value.push({
          url: item,
          name: arr[len - 1],
        });
      });
    });
  }, 100);
};
const editImageStr = ref("");
const handleEdit = () => {
  // 图片路径拼接,判断传回数组长度是否大于1
  if (editImage.value.length > 1) {
    let aa = "";
    editImage.value.forEach((item) => {
      aa += item + ",";
    });
    editImageStr.value = aa.substring(0, aa.length - 1);
  } else {
    editImageStr.value = String(editImage.value);
  }
  Myrequest("PUT", "/admin/v1/hotel/" + editID.value, {
    province: provinceEdit.value, //省
    city: secondCityEdit.value,//市
    district: areasValEdit.value,//区
    linkman: editContactsVal.value,//联系人
    address: editAddressVal.value,//详细地址
    phone: editPhoneVal.value,//手机号
    wechat: editWeichatVal.value,//微信号
    img_urls: editImageStr.value,//图片字符串
    logo_url: editLogoImage.value,//logo字符串
    name:editNameVal.value //酒店名称
  }).then((res) => {
    // Editvisible.value = false;

    // 强制页面刷新获取最新数据
    // location.reload();
  });
};

const bindClose = () => {
  filesEdit.value = [];
  filesLogoEdit.value = [];
};

// 禁用/启用按钮
const Disablevisible = ref(false);
const activeEn = ref("");
const bindDisable = (activeNum) => {
  Disablevisible.value = true;
  activeEn.value = activeNum;
};
// 禁用/启用确认执行
const handleDisable = () => {
  Disablevisible.value = false;
  console.log(editID.value);
  Myrequest("PUT", "/admin/v1/hotel/status/" + editID.value, {
    is_ban: activeEn.value,
  }).then((res) => {
    Refresh();
    // 强制页面刷新获取最新数据
    location.reload();
  });
};

const roomId = ref(""); // 房间ID
const passwordId = ref(""); // 密码ID
const customRowSub = (record) => {
  return {
    onClick: (event) => {
      console.log(record);
      roomId.value = record.id;
      if (record.RoomPassword.length > 0) {
        passwordId.value = record.RoomPassword[0].id;
      }
    },
  };
};

// 添加房间
const visibleRoom = ref(false);
const roomType = ref(); //类型
const roomIntroduce = ref(""); //房间简介
const roomDeposit = ref(""); //房间押金
const roomPrice = ref(""); //房间价格
const filesRoom = ref([]); //房间图片回显
const RoomImage = ref([]); //添加房间图片
const roomImageStr = ref(""); //房间图片字符串
const roomFrom = ref(""); //房间类型（例：一室单人房）
const roomDetail = ref(""); //房间类型（例：无早餐·整套·1居 1张 2*1.5米大床·1人）
const roomActive = ref();
const addRoom = (value) => {
  visibleRoom.value = true;
  roomActive.value = value;
  switch (roomActive.value) {
    case 0:
      activeNum.value = 2;
      break;
    case 1:
      activeNum.value = 2;
      setTimeout(() => {
        Myrequest("get", "/admin/v1/Room/" + roomId.value).then((res) => {
          console.log(res);
          roomType.value = res.data.status;
          roomIntroduce.value = res.data.content;
          roomDeposit.value = res.data.old_price;
          roomPrice.value = res.data.price;
          roomFrom.value = res.data.type;
          roomDetail.value = res.data.describe;
          res.data.img_url.forEach((item) => {
            let arr = item.split("/");
            let len = arr.length;
            RoomImage.value.push(item);
            console.log(RoomImage.value);
            filesRoom.value.push({
              url: item,
              name: arr[len - 1],
            });
          });
        });
      }, 10);
      break;
  }
};
// 房间状态
const ChangeRoomType = (value) => {
  roomType.value = value;
};
const handleAddRoom = () => {
  // 图片路径拼接,判断传回数组长度是否大于1
  if (RoomImage.value.length > 1) {
    let aa = "";
    RoomImage.value.forEach((item) => {
      aa += item + ",";
    });
    roomImageStr.value = aa.substring(0, aa.length - 1);
  } else {
    roomImageStr.value = String(RoomImage.value);
  }
  switch (roomActive.value) {
    case 0:
      console.log(roomImageStr.value);
      Myrequest("POST", "/admin/v1/Room", {
        hotel_id: hotelId.value, //酒店ID
        type: roomFrom.value, //房间类型（例：一室单人房）
        describe: roomDetail.value, //房间类型（例：无早餐·整套·1居 1张 2*1.5米大床·1人）
        content: roomIntroduce.value, //介绍
        img_url: roomImageStr.value, // 房间图片
        deposit: roomDeposit.value, // 定金
        price: roomPrice.value, // 价格
        status: roomType.value, //房间状态（是否出租）
      }).then((res) => {
        console.log(res);
        visibleRoom.value = false;
        message.success("添加成功");
        // 强制页面刷新获取最新数据
        location.reload();
      });
      break;
    case 1:
      console.log(RoomImage.value);
      console.log(roomImageStr.value);
      if (roomType.value === "未出租") {
        roomType.value = "0";
        return;
      }
      if (roomType.value === "已出租") {
        roomType.value = "1";
        return;
      }
      Myrequest("put", "/admin/v1/Room/" + roomId.value, {
        type: roomFrom.value,
        hotel_id: hotelId.value,
        content: roomIntroduce.value, //介绍
        img_url: roomImageStr.value, // 房间图片
        deposit: roomDeposit.value, // 定金
        price: roomPrice.value, // 价格
        describe: roomDetail.value,
        status: roomType.value, //房间状态（是否出租）
      }).then((res) => {
        console.log(res);
        switch (res.code) {
          case 200:
            message.success("修改成功");
            visibleRoom.value = false;
            Myrequest("get", "/admin/v1/Room/" + hotelId.value);
            // 强制页面刷新获取最新数据
            location.reload();
            break;
        }
      });
      break;
  }
};

// emptyRoom
const emptyRoom = () => {
  roomType.value = "";
  roomIntroduce.value = "";
  roomDeposit.value = "";
  roomPrice.value = "";
  filesRoom.value = [];
  RoomImage.value = [];
  roomImageStr.value = "";
  roomFrom.value = "";
  roomDetail.value = "";
};

// 房间密码添加
const visiblePassword = ref(false);
const valueTime = ref([]);
const passwordValue = ref(""); //密码
const startDate = ref(""), //开始时间
  endDate = ref(""); //结束时间

const addPassword = () => {
  setTimeout(() => {
    Myrequest("get", "/admin/v1/Room/" + roomId.value).then((res) => {
      if (res.data.RoomPassword.length > 0) {
        visiblePassword.value = false;
        message.warning("请先删除密码！！！！");
      } else {
        visiblePassword.value = true;
      }
    });
  }, 10);
};
const handleAddPassword = () => {
  startDate.value = getSimpleDate(valueTime.value[0].$d);
  endDate.value = getSimpleDate(valueTime.value[1].$d);
  console.log(startDate.value, endDate.value);
  Myrequest("POST", "/admin/v1/RoomPassword", {
    room_id: roomId.value,
    password: passwordValue.value,
    start_time: startDate.value,
    end_time: endDate.value,
  }).then((res) => {
    console.log(res);
    message.success("添加成功");
    visiblePassword.value = false;
    // 强制页面刷新获取最新数据
    location.reload();
  });
};

// 删除动作
const visibleDel = ref(false);
const delActive = ref();
const delText = ref("");
const del = (value) => {
  visibleDel.value = true;
  delActive.value = value;
  switch (delActive.value) {
    case 0:
      delText.value = "删除密码";
      break;
    case 1:
      delText.value = "删除房间";
      break;
  }
};
const handleDel = () => {
  switch (delActive.value) {
    case 0:
      Myrequest("delete", "/admin/v1/RoomPassword/" + passwordId.value).then(
        (res) => {
          console.log(res);
          message.success("删除成功");
          visibleDel.value = false;
          // 强制页面刷新获取最新数据
          location.reload();
        }
      );
      break;
    case 1:
      Myrequest("delete", "/admin/v1/Room/" + roomId.value).then((res) => {
        console.log(res);
        message.success("删除成功");
        visibleDel.value = false;
        // 强制页面刷新获取最新数据
        location.reload();
      });
      break;
  }
};

// 添加-文件上传
const handleChangeFile = (info) => {
  const { file } = info;
  console.log(file);
  if (file.status === "done") {
    switch (activeNum.value) {
      case 0:
        fileHotelFile.value.push(file.response.data);
        break;
      case 1:
        editImage.value.push(file.response.data);
        break;
      case 2:
        RoomImage.value.push(file.response.data);
        break;
    }
    switch (file.response.code) {
      case 501:
        console.log("上传失败");
        break;
    }
    console.log("上传完成");
  } else if (file.status === "error") {
    console.log("错误");
  } else if (file.status === "removed") {
    console.log(activeNum.value);
    console.log("文件已删除");
    // 文件删除将原先已保存的内容进行对应删除
    switch (activeNum.value) {
      case 0:
        fileHotelFile.value.splice(
          fileHotelFile.value.indexOf(file.response.data),
          1
        );
        break;
      case 1:
        editImage.value.splice(editImage.value.indexOf(file.url), 1);
        break;
      case 2:
        RoomImage.value.splice(RoomImage.value.indexOf(file.url), 1);
        break;
    }
  } else {
    console.log("上传中！！！！");
  }
};
const handleChangeLogo = (info) => {
  const { file } = info;
  if (file.status === "done") {
    switch (activeNum.value) {
      case 0:
        fileHotelLogo.value = file.response.data;
        break;
      case 1:
        editLogoImage.value = file.response.data;
        break;
    }

    switch (file.response.code) {
      case 501:
        console.log("上传失败");
        break;
    }
    console.log("上传完成");
  } else if (file.status === "error") {
    console.log("错误");
  } else if (file.status === "removed") {
    console.log("文件已删除");
    switch (activeNum.value) {
      case 0:
        fileHotelLogo.value = "";
        break;
      case 1:
        editLogoImage.value = "";
        break;
    }
  } else {
    console.log("上传中！！！！");
  }
};
</script>

<style lang="less">
.hotelMant {
  background: #fff;
  padding: 0 45px;
  .hotelMant-header {
    display: flex;
    align-items: center;
    height: 70px;
    border-bottom: 1px solid grey;
    .hotelMant-tit {
      width: 50%;
      height: 100%;
      display: flex;
      align-items: center;
      p {
        font-size: 20px;
        font-weight: bolder;
        margin: 0;
      }
    }
    .hotelMant-search {
      width: 50%;
      display: flex;
      justify-content: right;
      align-items: center;
    }
  }
  .hotelMant-headerFun {
    display: flex;
    align-items: center;
    height: 70px;
    .addHotel {
      padding: 25px 20px;
      display: flex;
      align-items: center;
      border-radius: 10px;
    }
  }
  .hotelMant-content {
    // height: 800px;
    .addHotel {
      padding: 25px 20px;
      display: flex;
      align-items: center;
      border-radius: 10px;
    }
  }
}
</style>